import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Box, Typography, Container, Snackbar, Alert } from '@mui/material';
import {
  ContentGrid,
  SearchFilter,
  LoadMore,
  ContentModal,
} from './components';
import { useContent, useInteraction } from '../../hooks';
import {
  ContentListItem,
  ContentQueryParams,
  OrderBy,
  TargetType,
} from '../../types';

const Home: React.FC = () => {
  // 状态管理
  const [contents, setContents] = useState<ContentListItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  // 使用 useMemo 避免每次渲染都创建新对象
  const initialSearchParams = useMemo(() => ({
    page: 1,
    size: 12,
    orderBy: OrderBy.CREATED_AT,
  }), []);
  
  const [searchParams, setSearchParams] = useState<ContentQueryParams>(initialSearchParams);

  // 模态框状态
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedContentId, setSelectedContentId] = useState<number | null>(null);

  // 提示信息
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success' as 'success' | 'error' | 'warning' | 'info',
  });

  // Hooks
  const { getPublicContents } = useContent();
  const { toggleLike } = useInteraction();

  // 加载内容列表
  const loadContents = useCallback(async (params: ContentQueryParams, isLoadMore = false) => {
    console.log('🔄 loadContents 被调用:', { params, isLoadMore });
    
    if (isLoadMore) {
      setLoadingMore(true);
    } else {
      setLoading(true);
      setError(null);
    }

    try {
      console.log('📡 开始调用 getPublicContents API...');
      const response = await getPublicContents(params);
      console.log('📦 API 响应:', response);
      
      // 检查响应数据格式
      let contentData;
      
      // 如果响应有code字段，说明是标准API格式
      if ((response as any).code !== undefined) {
        if ((response as any).code === 200) {
          contentData = (response as any).data;
          console.log('✅ 标准API格式，成功获取数据:', contentData);
        } else {
          console.error('❌ API 返回错误:', response);
          setError((response as any).message || '加载失败');
          return;
        }
      } 
      // 如果直接返回数据对象（包含total, contents等字段）
      else if ((response as any).contents !== undefined) {
        contentData = response;
        console.log('✅ 直接数据格式，成功获取数据:', contentData);
      }
      // 其他情况视为错误
      else {
        console.error('❌ 未知的响应格式:', response);
        setError('数据格式错误');
        return;
      }
      
      // 根据API文档，contents字段包含内容列表
      const newContents = (contentData as any).contents || [];
      console.log('📋 解析出的内容列表:', newContents);
      
      if (isLoadMore) {
        setContents(prev => [...prev, ...newContents]);
      } else {
        setContents(newContents);
      }
      
      // 检查是否还有更多数据
      const totalPages = (contentData as any).totalPages || Math.ceil((contentData as any).total / (params.size || 12));
      setHasMore((params.page || 1) < totalPages);
      setCurrentPage(params.page || 1);
      
      console.log('📊 分页信息:', { totalPages, hasMore: (params.page || 1) < totalPages, currentPage: params.page || 1 });
    } catch (err) {
      console.error('🚨 网络请求失败:', err);
      console.error('🔍 错误详情:', {
        message: (err as any).message,
        response: (err as any).response,
        status: (err as any).response?.status,
        data: (err as any).response?.data,
      });
      
      // 根据错误类型提供更具体的错误信息
      if ((err as any).response?.status === 404) {
        setError('API接口不存在，请检查后端服务');
      } else if ((err as any).response?.status === 500) {
        setError('服务器内部错误，请稍后重试');
      } else if ((err as any).code === 'NETWORK_ERROR' || (err as any).message?.includes('Network Error')) {
        setError('网络连接失败，请检查网络设置');
      } else {
        setError(`请求失败: ${(err as any).message || '未知错误'}`);
      }
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, [getPublicContents]);

  // 初始化加载
  useEffect(() => {
    loadContents(initialSearchParams);
  }, [loadContents, initialSearchParams]); // 使用稳定的初始参数

  // 搜索处理
  const handleSearch = useCallback((params: ContentQueryParams) => {
    setSearchParams(params);
    setCurrentPage(1);
    loadContents(params);
  }, [loadContents]);

  // 加载更多
  const handleLoadMore = useCallback(() => {
    if (hasMore && !loadingMore) {
      const nextPage = currentPage + 1;
      const params = { ...searchParams, page: nextPage };
      loadContents(params, true);
    }
  }, [hasMore, loadingMore, currentPage, searchParams, loadContents]);

  // 点赞处理
  const handleLike = useCallback(async (contentId: number) => {
    try {
      await toggleLike({ targetId: contentId, targetType: TargetType.CONTENT });
      
      // 更新本地状态
      setContents(prev => prev.map(content => 
        content.id === contentId 
          ? {
              ...content,
              isLiked: !content.isLiked,
              likeCount: content.isLiked ? content.likeCount - 1 : content.likeCount + 1,
            }
          : content
      ));

      setSnackbar({
        open: true,
        message: '操作成功',
        severity: 'success',
      });
    } catch (err) {
      setSnackbar({
        open: true,
        message: '操作失败，请稍后重试',
        severity: 'error',
      });
      console.error('点赞失败:', err);
    }
  }, [toggleLike]);

  // 评论处理（暂时只是打开模态框）
  const handleComment = useCallback((contentId: number) => {
    setSelectedContentId(contentId);
    setModalOpen(true);
  }, []);

  // 查看详情
  const handleView = useCallback((contentId: number) => {
    setSelectedContentId(contentId);
    setModalOpen(true);
  }, []);

  // 关闭模态框
  const handleCloseModal = useCallback(() => {
    setModalOpen(false);
    setSelectedContentId(null);
  }, []);

  // 关闭提示
  const handleCloseSnackbar = () => {
    setSnackbar(prev => ({ ...prev, open: false }));
  };

  return (
    <Container maxWidth="xl" sx={{ py: 3 }}>
      {/* 页面标题 */}
      <Box sx={{ mb: 4, textAlign: 'center' }}>
        <Typography 
          variant="h4" 
          component="h1" 
          gutterBottom
          sx={{ 
            fontWeight: 700,
            background: 'linear-gradient(45deg, #667eea 30%, #764ba2 90%)',
            backgroundClip: 'text',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
          }}
        >
          发现精彩内容
        </Typography>
        <Typography 
          variant="subtitle1" 
          color="text.secondary"
          sx={{ maxWidth: 600, mx: 'auto' }}
        >
          探索用户分享的精彩图片和视频，发现生活中的美好时刻
        </Typography>
      </Box>

      {/* 搜索筛选组件 */}
      <SearchFilter
        onSearch={handleSearch}
        loading={loading}
        initialParams={initialSearchParams}
      />

      {/* 内容网格 */}
      <ContentGrid
        contents={contents}
        loading={loading}
        error={error}
        onLike={handleLike}
        onComment={handleComment}
        onView={handleView}
        loadingMore={loadingMore}
      />

      {/* 加载更多组件 */}
      <LoadMore
        hasMore={hasMore}
        loading={loadingMore}
        onLoadMore={handleLoadMore}
        autoLoad={false}
      />

      {/* 内容详情模态框 */}
      <ContentModal
        open={modalOpen}
        contentId={selectedContentId}
        onClose={handleCloseModal}
        onLike={handleLike}
      />



      {/* 提示信息 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={snackbar.severity}
          variant="filled"
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default Home; 